package com.fsh.lingsp.common.common.intercepter;

import cn.hutool.extra.servlet.ServletUtil;
import com.fsh.lingsp.common.common.domain.dto.RequestInfo;
import com.fsh.lingsp.common.common.utils.RequestHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 作者：fsh
 * 日期：2024/03/01
 * <p>
 * 描述：拦截器 Intecepter
 *
 *  专门存放 用户的信息。
 */
@Component
public class CollectorIntecepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // token拦截器中将uid放在了request中， 现在取出来
        Long uid = Optional.ofNullable(request.getAttribute("uid"))
                .map(Object::toString)
                .map(Long::parseLong)
                .orElse(null);

        //hutool工具包，解析ip
        String clientIP = ServletUtil.getClientIP(request);
        //将用户信息村存放到 ThreadLocal 中
        RequestInfo requestInfo=new RequestInfo(clientIP,uid);
        RequestHolder.set(requestInfo);

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
